import { app, shell, BrowserWindow, ipcMain } from 'electron'
import FramePacker from './FramePacker'
import SerialportServer from './serialport.server'

export default class RS422Server {

  private serverMap = new Map()
  constructor() {
    this._framePacker = new FramePacker(0xcc, 0xbb)
    this.bindEvent()
  }
  bindEvent() {
    ipcMain.handle('RS422_TEST', async (event, params) => {

      const key = JSON.stringify(params.connect)
      let server = this.serverMap.get(key)
      if(!server) {
        server = new SerialportServer(params.connect)
        this.serverMap.set(key, server)
      }

      const parser = (msg) => {
        return this._framePacker.unpack(msg, this._framePacker.map.RS422_MESSAGE)
      }
      const acceptChecker = (message) => {
        return message.number === params.number && message.state === params.state
      }
      const buffer = this._framePacker.messagePacker(
        this._framePacker.map.RS422_MESSAGE.sendFormat,
        [0, params.number, params.state]
      )
      const result = await server.sendAsync(buffer, { parser, acceptChecker })
      return result
    })
  }


}
